<template>
  <div class="app-container h-full flex flex-col">
    <!-- <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane v-for="item in tabList" :key="item.name" :label="item.label" :name="item.name">
        {{ item.label }}
      </el-tab-pane>
    </el-tabs> -->
    <div class="search-bar">
      <el-form ref="queryFormRef" :inline="true" class="flex justify-between align-middle">
        <div class="search-bar-left p-l-3">
          <el-form-item prop="categoryId" label="商品分类">
            <CategoryCascader v-model="categoryId" :defaultParams="{ selfOwn: true }" />
            <!-- <el-select v-model="categoryId" placeholder="商品分类" clearable style="width: 200px">
              <el-option
                v-for="item in goodsCategoryList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> -->
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" @click="initList">搜索</el-button>
            <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
          </el-form-item>
        </div>
        <div class="search-bar-right">
          <el-form-item>
            <el-button type="primary" @click="addProduct">添加商品</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <base-page-table
      class="flex-1 bg-white p-2"
      :table-data="products"
      :loading="loading"
      :pageNum="pageNum"
      :pageSize="pageSize"
      :total="total"
      :table-columns-data="tableColumns"
      @handleQuery="handleQuery"
    >
      <template #topImage="scope">
        <el-image
          :src="handleImageUrl(scope.row.topImage)"
          style="width: 60px; height: 60px"
          :preview-src-list="[handleImageUrl(scope.row.topImage)]"
          preview-teleported="true"
        >
          <template #error>
            <div class="image-slot">
              <el-icon><icon-picture /></el-icon>
            </div>
          </template>
        </el-image>
      </template>
      <template #showFlag="scope">
        <el-switch
          v-model="scope.row.showFlag"
          :active-value="1"
          :inactive-value="0"
          :before-change="() => toggleProductSale(scope.row)"
        />
      </template>
      <template #category="scope">
        {{ goodsCategoryObject[scope.row.categoryId] }}
      </template>
      <template #actions="scope">
        <el-button type="primary" link icon="edit" @click.stop="editProduct(scope.row)">
          编辑
        </el-button>
        <el-button type="danger" link icon="delete" @click.stop="deleteProduct(scope.row.id)">
          删除
        </el-button>
      </template>
    </base-page-table>
    <AddGood
      v-model:dialogShow="addGoodVisible"
      :default-data="defaultData"
      :title="defaultData ? '编辑商品' : '添加商品'"
      @initList="initList"
      @editGood="editGoodFunc"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import GoodAPI from "@/api/good";
import { useDictStore } from "@/store/modules/dict";
import BasePageTable from "@/components/BasePageTable/index.vue";
import CategoryCascader from "@/components/CategoryCascader/index.vue";
import AddGood from "./AddGood.vue";
import { useUserStore } from "@/store/modules/user";
const userStore = useUserStore();
const loading = ref(false);
const products = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const queryFormRef = ref();
const categoryId = ref("");

const reallyUrl = import.meta.env.VITE_API_IMAGE;
const handleImageUrl = (url) => {
  return `${JSON.parse(url)[0].url}`;
};
const tableColumns = ref([
  {
    prop: "title",
    label: "商品名称",
    showOverflowTooltip: true,
  },
  {
    prop: "categoryName",
    label: "商品分类",
    showOverflowTooltip: true,
  },
  {
    prop: "topImage",
    label: "主图",
    showOverflowTooltip: true,
    customSlot: "topImage",
  },
  {
    prop: "price",
    label: "价格",
    showOverflowTooltip: true,
  },
  {
    prop: "showFlag",
    label: "是否展示",
    showOverflowTooltip: true,
    customSlot: "showFlag",
  },
  {
    prop: "actions",
    label: "操作",
    width: 200,
    customSlot: "actions",
    showOverflowTooltip: true,
  },
]);
const handleResetQuery = () => {
  categoryId.value = "";
  initList();
};
const initList = () => {
  pageNum.value = 1;
  fetchProducts();
};
const fetchProducts = async () => {
  console.log(categoryId.value);

  loading.value = true;
  try {
    const data = await GoodAPI.getGoodsList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      categoryId: categoryId.value,
      companyId: userStore.userInfo.companyId,
    });
    products.value = data.list;
    total.value = data.total;
  } catch (error) {
    console.error("Failed to fetch products:", error);
  } finally {
    loading.value = false;
  }
};
/**
 * 分页
 * @param params
 */
const handleQuery = (params) => {
  pageNum.value = params.pageNum;
  pageSize.value = params.pageSize;
  fetchProducts();
};
const defaultData = ref(null);
// 打开编辑弹框
const editProduct = (product) => {
  defaultData.value = product;
  addGoodVisible.value = true;
};
const editGoodFunc = async (product) => {
  try {
    await GoodAPI.editGood({
      id: product.id,
      title: product.title,
      categoryId: product.categoryId,
      showFlag: product.showFlag,
      topImage: product.topImage,
      price: product.price,
      images: product.images,
      remark: product.remark,
    });
    ElMessage.success("编辑成功");
    addGoodVisible.value = false;
    initList();
  } catch (error) {
    console.log(error);
  }
};
const deleteProduct = async (id) => {
  try {
    ElMessageBox.confirm("确定要删除商品吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      await GoodAPI.deleteGood(id);
      ElMessage.success("删除成功");
      initList();
    });
  } catch (error) {
    console.log(error);
  }
};

const toggleProductSale = (product) => {
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm("确定要修改商品状态吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      try {
        await editGoodFunc({
          ...product,
          showFlag: product.showFlag === 1 ? 0 : 1,
        });
        resolve(true);
      } catch (error) {
        reject(false);
      }
    });
  });
};
/**
 * 添加商品弹窗
 *
 */
const addGoodVisible = ref(false);
const addProduct = () => {
  defaultData.value = null;
  addGoodVisible.value = true;
};

const dictStore = useDictStore();
const goodsCategoryObject = ref({});
const goodsCategoryList = ref([]);
onMounted(async () => {
  // if (dictStore.getDictionary("goodsCategory").length === 0) {
  //   await getGoodsCategoryList();
  // }
  goodsCategoryList.value = dictStore.getDictionary("goodsCategory");
  dictStore.getDictionary("goodsCategory").forEach((item) => {
    goodsCategoryObject.value[item.value] = item.label;
  });
  fetchProducts();
});
</script>

<style scoped></style>
